#pragma once
#include <sys/poll.h>
#include "comm.hpp"
#include "Socket.hpp"
#include "Log.hpp"

using namespace SocketModule;
using namespace LogModule;

class PollServer
{
    const static int size = 4096; 
    const static int defaultfd = -1;

public:
    PollServer(uint16_t port) : _listensocket(std::make_unique<TcpSocket>()), _isrunning(false)
    {
        _listensocket->BuildTcpSocket(port);
        for (int i = 0; i < size; i++)
        {
            _fds[i].fd = defaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }
        _fds[0].fd = _listensocket->Fd();
        _fds[0].events = POLLIN;
    }

    void Start()
    {
        _isrunning = true;
        int timeout = 1000;
        while (true)
        {
            int n = poll(_fds, size, timeout);
            switch (n)
            {
            case -1:
                LOG(LogLevel::ERROR) << "select error";
                break;
            case 0:
                LOG(LogLevel::INFO) << "time out";
                break;
            default:
                LOG(LogLevel::DEBUG) << "有事件就绪..";
                Dispatcher();
                break;
            }
        }
    }

    // 事件派发
    void Dispatcher()
    {
        for (int i = 0; i < size; i++)
        {
            if (_fds[i].fd == defaultfd)
                continue;
            if (_fds[i].revents & POLLIN)
            {
                if (_fds[i].fd == _listensocket->Fd())
                {
                    Accepter();
                }
                else
                {
                    Recver(i);
                }
            }
        }
    }

    // 连接管理器
    void Accepter()
    {
        InetAddr client;
        int sockfd = _listensocket->Accept(&client);
        if (sockfd >= 0)
        {
            LOG(LogLevel::INFO) << "A new sockfd come: " << sockfd
                                << ", client: " << client.StringAddr();
            int pos = 0;
            for (; pos < size; pos++)
            {
                if (_fds[pos].fd == defaultfd)
                    break;
            }
            if (pos == size)
            {
                LOG(LogLevel::WARNING) << "select server full";
                close(sockfd);
            }
            else
            {
                _fds[pos].fd = sockfd;
                _fds[pos].events = POLLIN;
                _fds[pos].revents = 0;
            }
        }
    }

    // IO接收器
    void Recver(int pos)
    {
        char buff[1024];
        ssize_t n = recv(_fds[pos].fd, buff, sizeof(buff)-1, 0);
        if(n > 0)
        {
            buff[n] = 0;
            std::cout << "client say: " << buff;
        }
        else if(n == 0)
        {
            LOG(LogLevel::INFO) << "client quit";
            close(_fds[pos].fd);
            _fds[pos].fd = defaultfd;
        }
        else
        {
            close(_fds[pos].fd);
            LOG(LogLevel::INFO) << "recv error";
        }
    }

    void Stop()
    {
        _isrunning = false;
    }

    ~PollServer() {}

private:
    std::unique_ptr<Socket> _listensocket;
    bool _isrunning;
    
    struct pollfd _fds[size];
};